package cn.wangkai.peanut.action.util;

import java.io.OutputStream;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import cn.wangkai.peanut.db.util.BeanUtil;
import cn.wangkai.peanut.util.RequestContext;
import cn.wangkai.peanut.util.mvc.ActionForward;

public class BaseAction {
	private static final Log log = LogFactory.getLog(BaseAction.class);

	/**
	 * 导出Excel
	 * @param context 
	 * @param conn	数据库链接
	 * @param headRow1	表头信息
	 * @param SQL	sql数据库
	 * @param Filename	导出文件名
	 * @return
	 * @throws Exception
	 */
	public ActionForward toExcel(RequestContext context, Connection conn,
			String[] headRow1, String SQL,String Filename) throws Exception {
		if(StringUtils.isBlank(Filename)) Filename="excel";
		HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件
		HSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet
		HSSFCellStyle headstyle = workbook.createCellStyle();// 创建一个单元的样式
		// 填充模式
		HSSFFont font = workbook.createFont();
		font.setFontName("黑体");
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
		headstyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);// 上下居中
		headstyle.setFont(font);
		int rowint = 0;
		if(headRow1!=null){
			HSSFRow row = sheet.createRow((short) rowint);
			for (int i = 0; i < headRow1.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(headRow1[i]);
				cell.setCellStyle(headstyle);
			}
		}
		Statement stmt = null;
		ResultSet rs = null;
		if (StringUtils.isNotBlank(SQL)&&conn!=null) {
			try {
				// 查询页码数据
				stmt = conn.createStatement();
				rs = stmt.executeQuery(SQL);
				ResultSetMetaData rowcol = rs.getMetaData();
				int rowi = rowcol.getColumnCount();
				while (rs.next()) {
					rowint++;
					HSSFRow rowdate = sheet.createRow((short) rowint);
					for (int j = 1; j <= rowi; j++) {
						try {
							HSSFCell cell = rowdate.createCell(j - 1);
							String typename = rowcol.getColumnTypeName(j);
							if (typename != null) {
								if ("CLOB".equals(typename)) {
									Clob tmpblob = rs.getClob(j);
									Reader out = tmpblob.getCharacterStream();
									int js = (int) tmpblob.length();
									char[] ctmp = new char[js];
									out.read(ctmp);
									out.close();
									cell.setCellValue(new String(ctmp));
								} else {
									cell.setCellValue(rs.getString(j));
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							log.error(e);
						}
					}
				}
				rs.close();
			} catch (SQLException e) {
				log.error(e);
			} catch (Exception e) {
				log.error(e);
			} finally {
				try {
					if (rs != null) {
						rs.close();
						rs = null;
					}
				} catch (Exception e) {
					log.error(e);
				}
				try {
					if (stmt != null) {
						stmt.close();
						stmt = null;
					}
				} catch (Exception e) {
					log.error(e);
				}
			}
		}
		OutputStream out = context.response().getOutputStream();
		context.response().setContentType(
				"application/vnd.ms-excel;charset=UTF-8");
		context.response()
				.setHeader("Content-Type", "application/octet-stream");
		context.response().addHeader(
				"Content-Disposition",
				new String(("attachment; filename=\""+Filename+".xls\"")
						.getBytes("GBK"), "ISO-8859-1"));
		workbook.write(out);
		out.close();
		return new ActionForward("tofile");
	}

	public static String getJsonMessage(boolean succees, String msg) {
		JSONObject json = new JSONObject();
		try {
			json.put("succees", new Boolean(succees));
			json.put("msg", msg);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json.toJSONString();
	}

	public static Object getRequestBean(HttpServletRequest request,
			@SuppressWarnings("rawtypes") Class type) throws SQLException {
		HashMap<String, Object> rsh = new HashMap<String, Object>();
		BeanUtil beanUtil = new BeanUtil();
		@SuppressWarnings("unchecked")
		Map<String, Object> params = request.getParameterMap();
		Iterator<Map.Entry<String, Object>> iter = params.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iter.next();
			String key = entry.getKey().toString();
			Object obj = entry.getValue();
			rsh.put(key, obj);
		}
		return beanUtil.toBean(rsh, type);

	}
}
